﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GameSchool.Models.Interfaces;

namespace GameSchool.Models.Repositories
{
    public class AssignmentRepository 
    {
        GameSchoolDBDataContext db = new GameSchoolDBDataContext();
        
        public IQueryable<Assignment> GetAssignments()
        {
            return db.Assignments;
        }

        //Fetch an assignment by it's ID
        public Assignment GetAssignmentByID(int? aID)
        {
            var lec = (
                          from Assignment in db.Assignments
                          where Assignment.ResourceID == aID
                          where Assignment.AssignmentType == "Lecture"
                          select Assignment).SingleOrDefault();
            return lec;
        }

        //Checks if a student has already got points for viewing a lecture
        //If data exists on the assignment in the AssignmentScore table he has already gotten points.
        public AssignmentScore CheckIfCompletedByID(Guid uID, int? id)
        {
            var exists = (
                          from AssignmentScore in db.AssignmentScores
                          where AssignmentScore.UserID == uID
                          where AssignmentScore.AssignmentID == id
                          select AssignmentScore).SingleOrDefault();
            return exists;
        }

        public void AddAssignment(Assignment a)
        {
            db.Assignments.InsertOnSubmit(a);
        }

        public void AddAssignmentScore(AssignmentScore ass)
        {
            db.AssignmentScores.InsertOnSubmit(ass);
        }

        //Finds an assignment by it's ID and deletes it from the table
        public void DeleteAssignment(int? aID)
        {
            var ass = (from n in db.Assignments
                       where n.ID == aID
                       select n).SingleOrDefault();
            if (ass != null)
            {
                db.Assignments.DeleteOnSubmit(ass);
            }
        }
     
        public void Save()
        {
            db.SubmitChanges();
        }
    }
}